<template>
  <!-- 筛选 -->
  <div class="search-box">
    <el-row :gutter="20">
      <el-col :span="5">
        <span>课程名称</span>
        <el-input v-model="productTitle"></el-input>
      </el-col>
      <el-col :span="5">
        <span>课程类型</span>
        <disProductType-sl v-model="productType"></disProductType-sl>
      </el-col>
      <el-col :span="5">
        <span>分销状态</span>
        <disState-sl v-model="enabled"></disState-sl>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="5">
        <span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;售价&nbsp;</span>
        <el-input placeholder="￥" v-model="price_l"></el-input>
        <em>-</em>
        <el-input placeholder="￥" v-model="price_r"></el-input>
      </el-col>
      <el-col :span="5">
        <span>佣金比例&nbsp;</span>
        <el-input placeholder="%" v-model="rate_l"></el-input>
        <em>-</em>
        <el-input placeholder="%" v-model="rate_r"></el-input>
      </el-col>
    </el-row>
  </div>
  <!-- 按钮 -->
  <div class="btn-box">
    <el-button type="success" @click="getList">刷新</el-button>
    <el-button type="primary" @click="search">查询</el-button>
    <el-button @click="resetSearch">清空</el-button>
    <data-pool></data-pool>
    <el-button
      type="danger"
      icon="el-icon-close"
      :disabled="state.multipleSelection.length === 0"
      @click="del"
    >
      删除
    </el-button>
    <el-button
      type="primary"
      icon="el-icon-edit"
      :disabled="state.multipleSelection.length === 0"
      @click="mutiEdit"
    >
      批量修改分销产品
    </el-button>
    <el-button
      type="primary"
      icon="el-icon-edit"
      :disabled="state.multipleSelection.length === 0"
      @click="mutiAllowOrBan(1)"
    >
      批量允许分销
    </el-button>
    <el-button
      type="primary"
      icon="el-icon-edit"
      :disabled="state.multipleSelection.length === 0"
      @click="mutiAllowOrBan(0)"
    >
      批量禁止分销
    </el-button>
    <el-button type="primary" icon="el-icon-check" :disabled="!isDraw" @click="saveSort">
      保存顺序
    </el-button>
  </div>
  <!-- 列表 -->
  <el-table
    :data="state.disData"
    style="width: 100%; margin-top: 10px"
    border
    tooltip-effect="dark"
    row-key="id"
    v-loading="tableLoading"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55px"></el-table-column>
    <!-- <el-table-column prop="productId" label="产品ID" align="center" show-overflow-tooltip></el-table-column> -->
    <el-table-column prop="productType" label="产品类型" align="center" show-overflow-tooltip>
      <template #default="scope">
        {{
          scope.row.productType === undefined
            ? ''
            : $selectFormat['disProductTypeSl'](scope.row.productType).label
        }}
      </template>
    </el-table-column>
    <el-table-column prop="showProductAmount" label="产品价格" align="center" show-overflow-tooltip>
      <template #default="scope">{{ scope.row.showProductAmount }}元</template>
    </el-table-column>
    <el-table-column
      prop="productTitle"
      label="产品名称"
      align="center"
      show-overflow-tooltip
    ></el-table-column>
    <el-table-column prop="enabled" label="分销状态" align="center" show-overflow-tooltip>
      <template #default="scope">
        {{
          scope.row.enabled === undefined
            ? ''
            : $selectFormat['disStateSl'](scope.row.enabled).label
        }}
      </template>
    </el-table-column>
    <el-table-column prop="percent" label="分佣比例" align="center" show-overflow-tooltip>
      <template #default="scope">
        {{ scope.row.percent }}%
        <span v-if="scope.row.indirectPercent">- [间接{{ scope.row.indirectPercent }}%]</span>
      </template>
    </el-table-column>
    <el-table-column prop="showSaleAmount" label="佣金金额" align="center" show-overflow-tooltip>
      <template #default="scope">{{ scope.row.showSaleAmount }}元</template>
    </el-table-column>
    <el-table-column label="操作" align="center" width="350px">
      <template #default="scope">
        <div>
          <el-button type="primary" @click="disProportion(scope.row)">分销及比例设置</el-button>
          <el-button type="primary" @click="modelMessage(scope.row)">模板文案</el-button>
          <el-button icon="el-icon-rank">点我拖动</el-button>
        </div>
      </template>
    </el-table-column>
  </el-table>
  <!-- Rate Dialog -->
  <el-dialog v-model="rateDialogVisible" title="比例设置" center>
    <div class="rateDialog">
      <el-row>
        <span>设置为分销课程</span>
        <el-switch
          v-model="state.rateData.enabled"
          active-color="#13ce66"
          :active-value="1"
          :inactive-value="0"
          inactive-color="#ff4949"
        ></el-switch>
      </el-row>
      <el-row>
        <span>比例设置</span>
        <el-radio-group v-model="state.rateData.isDefault">
          <el-radio :label="1">使用默认比例</el-radio>
          <el-radio :label="0">自定义比例</el-radio>
        </el-radio-group>
      </el-row>
      <el-row>
        <table>
          <tr>
            <td>推广员</td>
            <td>直接推广佣金比例</td>
            <td>间接推广佣金比例</td>
          </tr>
          <tr>
            <td>普通推广员</td>
            <td class="define-rate">
              <div>请输入0-80的数字</div>
              <el-input-number
                v-model="state.rateData.percent"
                :min="0"
                :max="80"
                :disabled="state.rateData.isDefault == 1"
              ></el-input-number>
              %
            </td>
            <td class="define-rate">
              <div>请输入0-80的数字</div>
              <el-input-number
                v-model="state.rateData.indirectPercent"
                :min="0"
                :max="80"
                :disabled="state.rateData.isDefault == 1"
              ></el-input-number>
              %
            </td>
          </tr>
        </table>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="rateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rateSubmit" v-permission="['dis:rule:edit']">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- content Dialog -->
  <el-dialog v-model="contentDialogVisible" title="推广模版文案设置" center>
    <div class="contentDialog">
      <!-- <el-row>
        <span>比例设置</span>
        <el-radio-group v-model="content">
          <el-radio :label="1">使用默认文案</el-radio>
          <el-radio :label="2">自定义文案</el-radio>
        </el-radio-group>
      </el-row> -->
      <el-row>
        <span>文案</span>
        <textarea
          style="margin-bottom: 20px"
          rows="5"
          placeholder="请填写或者选择下方的文案"
          v-model="state.contentData.prompt"
        />
        <el-radio-group v-model="state.contentData.prompt">
          <el-radio
            v-for="(item, index) in state.moRenData.prompts"
            :key="index"
            :label="item.prompt"
          >
            {{ item.prompt }}
          </el-radio>
        </el-radio-group>
        <!-- <el-select v-model="state.contentData.prompt" placeholder="请选择1">
            <el-option
              v-for="(item, index) in state.moRenData.prompts"
              :key="index"
              placeholder="请5选择"
              :label="item.prompt"
              :value="item.prompt"
            ></el-option>
          </el-select> -->
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="contentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="contentSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 批量修改 dialog-->
  <el-dialog v-model="mutiDeitDialogVisible" title="多选设置比例文案" center>
    <div class="mutiDeitDialog">
      <el-row>
        <span>比例（默认为百分数，不需要输入百分比）：</span>
        <el-input v-model="mutiRata" type="number" :step="0.1" :max="80" :min="0"></el-input>
      </el-row>
      <el-row>
        <span>文案：</span>
        <el-input type="textarea" v-model="mutiContent"></el-input>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="mutiDeitReset">取 消</el-button>
        <el-button type="primary" @click="mutiDeitSubmit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
  import {
    defineProps,
    getCurrentInstance,
    onMounted,
    reactive,
    ref,
    watch,
    computed,
    onBeforeMount,
  } from 'vue';

  import Sortable from 'sortablejs';

  import { ElMessage } from 'element-plus';

  import DataPool from '@/components/DataPool.vue';

  // 这个就是事件总线哦
  import bus from '@/bus';

  const {
    $url: url,
    $http: http,
    $service: service,
    JSON_HEADER: JSON_HEADER,
    $selectFormat: selectFormat,
  } = getCurrentInstance().appContext.config.globalProperties;

  // 比例设置Dialog
  const rateDialogVisible = ref(false);
  // 推广模版文案设置Dialog
  const contentDialogVisible = ref(false);
  // 多选编辑Dialog
  const mutiDeitDialogVisible = ref(false);

  // 表格loading
  const tableLoading = ref(false);
  // 筛选数据
  const productTitle = ref('');
  const productType = ref('');
  const enabled = ref('');
  const price_l = ref('');
  const price_r = ref('');
  const rate_l = ref('');
  const rate_r = ref('');

  // 是否拖动了
  const isDraw = ref(false);

  // dialog
  const rate = ref(-1);

  const content = ref(-1);

  // 批量设置数据
  const mutiRata = ref('');
  const mutiContent = ref('');

  const state = reactive({
    // 数据源
    disData: [],
    // 选中
    multipleSelection: [],
    // 比例设置时候的数据源
    rateData: [],
    // 文案设置时的数据源
    contentData: [],
    // 默认数据
    moRenData: [],
  });

  // methods
  // 得到数据
  const getList = () => {
    tableLoading.value = true;

    service.SaleProductList().then((res) => {
      tableLoading.value = false;
      state.disData = res;
      isDraw.value = false;
    });
  };
  // 复选框选择
  const handleSelectionChange = (val) => {
    state.multipleSelection = val;
  };
  // 新增分销产品
  bus.$on('dataPoolSelect',(val) => {
    let obj = val;
    obj.id ? delete obj.id : '';
    obj.cateId = obj.categoryId || '';
    obj.cateTitle = obj.categoryName || '';
    obj.productTitle = obj.title || obj.vipName || '';
    obj.productAmount = obj.price || obj.payPrice || '';
    obj.productCover = obj.cover || '';
    obj.payMode = obj.payMode || '';

    // 赋值
    // state.disData.unshift(val)
    service
      .SaleProductSave(
        {
          ...obj,
        },
        JSON_HEADER,
      )
      .then((res) => {
        ElMessage({ showClose: true, message: '添加成功！', type: 'success' });
        getList();
      });
  });
  // 保存顺序
  const saveSort = () => {
    let arr = [];
    state.disData.forEach((item, index) => {
      arr.push({
        ...item,
        sortnum: index,
      });
    });
    service.SaleProductSort(arr, JSON_HEADER).then((res) => {
      ElMessage({ showClose: true, message: '排序成功！', type: 'success' });
      getList();
    });
  };
  // 删除
  const del = () => {
    service
      .SaleProductDelete({
        ids: state.multipleSelection
          .map((item) => {
            return item.id;
          })
          .join(','),
      })
      .then((res) => {
        ElMessage({ showClose: true, message: '删除成功！', type: 'success' });
        getList();
      });
  };
  // 查询
  const search = () => {
    // 拼接
    let percent = '';
    let productAmount = '';
    percent = rate_l.value && rate_r.value ? rate_l.value + ',' + rate_r.value : '';
    // 乘以100是因为后端是按照分钱筛选
    productAmount =
      price_l.value && price_r.value ? price_l.value * 100 + ',' + price_r.value * 100 : '';
    // 请求
    tableLoading.value = true;
    // 筛选就用这个
    http(
      `${url.SaleProductList}?enabled=${enabled.value}&percent=${percent}&productAmount=${productAmount}&productTitle=${productTitle.value}&productType=${productType.value}`,
    ).then((res) => {
      tableLoading.value = false;
      state.disData = res;
    });
  };
  // 清空
  const resetSearch = () => {
    rate_l.value = '';
    rate_r.value = '';
    price_l.value = '';
    price_r.value = '';
    enabled.value = '';
    productType.value = '';
    productTitle.value = '';
    // 调用搜索
    search();
  };
  // 分销及比例设置
  const disProportion = (val) => {
    state.rateData = JSON.parse(JSON.stringify(val));
    rateDialogVisible.value = true;
  };
  // 比例提交
  const rateSubmit = () => {
    service.SaleProductSave(state.rateData, JSON_HEADER).then((res) => {
      ElMessage({ showClose: true, message: '修改成功！', type: 'success' });
      rateDialogVisible.value = false;
      getList();
    });
  };
  // 模板文案
  const modelMessage = (val) => {
    state.contentData = JSON.parse(JSON.stringify(val));
    // 这里应该是可以删除了
    for (let i = 0; i < state.moRenData.prompts.length; i++) {
      if (state.moRenData.prompts[i] === state.contentData.prompt) {
        content.value = 1;
        break;
      } else {
        content.value = 2;
      }
    }
    contentDialogVisible.value = true;
  };
  // 文案提交
  const contentSubmit = () => {
    service.SaleProductSave(state.contentData, JSON_HEADER).then((res) => {
      ElMessage({ showClose: true, message: '修改成功！', type: 'success' });
      contentDialogVisible.value = false;
      getList();
    });
  };
  // 批量修改
  const mutiEdit = () => {
    mutiDeitDialogVisible.value = true;
  };
  // 批量修改取消
  const mutiDeitReset = () => {
    mutiDeitDialogVisible.value = false;
    mutiRata.value = '';
    mutiContent.value = '';
  };
  // 批量修改提交
  const mutiDeitSubmit = () => {
    let str = '';
    str = state.multipleSelection
      .map((item) => {
        return item.id;
      })
      .join(',');
    service
      .SaleProductBatchUpdatePercent({
        ids: str,
        percent: mutiRata.value,
        prompt: mutiContent.value,
      })
      .then((res) => {
        ElMessage({ showClose: true, message: '修改成功！', type: 'success' });
        mutiDeitDialogVisible.value = false;
        mutiRata.value = '';
        mutiContent.value = '';
        getList();
      });
  };
  // 批量允许分销或者禁止分销---1代表允许，0代表禁止
  const mutiAllowOrBan = (val) => {
    let str = '';
    str = state.multipleSelection
      .map((item) => {
        return item.id;
      })
      .join(',');
    service
      .SaleProductBatchUpdateEnable({
        ids: str,
        enable: val,
      })
      .then((res) => {
        ElMessage({ showClose: true, message: '修改成功！', type: 'success' });
        getList();
      });
  };
  // 行排序
  const rowDrop = () => {
    // 此时找到的元素是要拖拽元素的父容器
    const tbody = document.querySelector('.el-table__body-wrapper tbody');
    Sortable.create(tbody, {
      // 指定父元素下可被拖拽的子元素
      draggable: '.el-table__row',
      onEnd({ newIndex, oldIndex }) {
        isDraw.value = true;
        const currRow = state.disData.splice(oldIndex, 1)[0];
        state.disData.splice(newIndex, 0, currRow);
      },
    });
  };

  watch(
    () => state.rateData.isDefault,
    () => {
      if (state.rateData.isDefault == 1) {
        state.rateData.percent = state.moRenData.percent;
        state.rateData.indirectPercent = state.moRenData.indirectPercent;
      }
    },
  );

  // 生命周期
  onBeforeMount(() => {
    // 得到默认数据
    service.SaleRuleInfo().then((res) => {
      state.moRenData = res;
    });
  });

  onMounted(() => {
    // 得到数据
    getList();
    // 行排序
    rowDrop();
  });
</script>
<style lang="less" scoped>
  // 筛选
  .search-box {
    :deep .el-row {
      margin-bottom: 10px;
      .el-col-5 {
        display: flex;
        span {
          display: inline-block;
          height: 32px;
          line-height: 32px;
          width: 80px;
          white-space: nowrap;
        }
        em {
          height: 32px;
          line-height: 32px;
        }
      }
    }
    :deep(.el-select .el-input .el-select__caret) {
      margin-left: 50px;
    }
  }
  // 按钮
  .btn-box {
    display: flex;
    margin-top: 10px;
  }
  .el-dialog {
    // 比例设置弹出框
    .rateDialog {
      .el-row {
        margin-bottom: 20px;
        span {
          margin-right: 10px;
        }
        .el-radio {
          margin: 0px 20px;
        }
        table {
          width: 100%;
          border-collapse: collapse;
          text-align: center;
          tr {
            td {
              padding: 10px 0px;
              border: 1px solid #000;
            }
            .define-rate {
              input {
                width: 70px;
                outline: 0;
              }
            }
          }
        }
      }
    }
    // 推广模版文案设置弹出框
    .contentDialog {
      .el-row {
        margin-bottom: 20px;
        span {
          margin-right: 10px;
        }
        .el-radio {
          margin: 0px 10px;
        }
        textarea {
          width: 93%;
          padding: 10px;
          font-family: '"Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","微软雅黑",Arial,sans-serif;';
        }
      }
    }
  }
</style>
